# -*- coding: utf-8 -*-
"""
@Time ： 2021/3/20 20:55
@Auth ： 买菠萝凤梨
@File ：base_requests.py
@IDE ：PyCharm
@Motto：work steadily

"""
import requests
import json as exchangejson
from public.log import Log

log = Log()


class Requests:
    def __init__(self):
        # 获取cookies的持久性,连接和配置
        self.session = requests.sessions.Session()

    def get(self, url, **kwargs):
        return self.http_requests(url, 'GET', **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        return self.http_requests(url, 'POST', data, json, **kwargs)

    def delete(self, url, **kwargs):
        return self.http_requests(url, 'DELETE', **kwargs)

    def put(self, url, data, **kwargs):
        return self.http_requests(url, 'PUT', data, **kwargs)

    def patch(self, url, data, **kwargs):
        return self.http_requests(url, 'PATCH', data, **kwargs)

    def http_requests(self, url, method, data=None, json=None, **kwargs):
        # 提取传入的字典内容
        headers = dict(**kwargs).get('headers')
        params = dict(**kwargs).get('params')
        self.requests_log(url, method, data, headers, params)
        if method == 'GET':
            return self.session.get(url, **kwargs)
        elif method == 'POST':
            return self.session.post(url, data, json, **kwargs)
        elif method == 'DELETE':
            return self.session.delete(url, **kwargs)
        elif method == 'PUT':
            # 判断传入的数据是否为json字符串，如果不是讲字典转换为json字符串
            if json:
                data = exchangejson.dumps(json)
            return self.session.put(url, data, **kwargs)
        elif method == 'PATCH':
            if json:
                data = exchangejson.dumps(json)
            return self.session.patch(url, data, **kwargs)

    def requests_log(self, url, method, data=None, headers=None, params=None):
        log.info('访问的url：{}'.format(url))
        log.info('使用的方法为：{}'.format(method))
        # Python3中，json在做dumps操作时，会将中文转换成unicode编码，因此设置 ensure_ascii=False
        log.info('传入的数据为{}'.format(exchangejson.dumps(data,indent=4,ensure_ascii=False)))
        log.info('请求头为{}'.format(exchangejson.dumps(headers,indent=4,ensure_ascii=False)))
        log.info('传入的相关参数为：{}'.format(exchangejson.dumps(params,indent=4,ensure_ascii=False)))


if __name__ == '__main__':
    api = Requests().get('https://www.tianqiapi.com/api/?version=v1&cityid=101110101')
    api1 = requests.sessions.Session().get('https://www.tianqiapi.com/api/?version=v1&cityid=100011')
    print(api)
    print(api1)


